﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeEdu.MODEL;
using LeEdu.BLL;
using System.IO;
using LeEdu.DAL;
using LeEdu.Entity;
using LeEdu.Service;


namespace LeEdu.Web.Controllers
{
    public class CourseController : Controller
    {
		/// <summary>
		/// 试题BLL
		/// </summary>
		QuestionsService qservice = new QuestionsService();
        /// <summary>
        /// 课程管理主页
        /// </summary>
        BLL.CourseBLL cbll = new CourseBLL();


        /// <summary>
        /// 学院CollegeBLL
        /// </summary>
        CollegeBLL cobll = new CollegeBLL();

        /// <summary>
        /// 实例化CourseBLL
        /// </summary>
        CourseBLL coursebll = new CourseBLL();


        /// <summary>
        /// 实例化CollegeBLL
        /// </summary>
        CollegeBLL collegebll = new CollegeBLL();

        /// <summary>
        /// 实例化
        /// </summary>
        LableBLL lablebll = new LableBLL();

        /// <summary>
        /// 实例化HourBLL
        /// </summary>
        HourBLL hourbll = new HourBLL();

        /// <summary>
        /// 实例化FilesBLL
        /// </summary>
        FilesBLL filesbll = new FilesBLL();


        /// <summary>
        /// 实例化-
        /// </summary>
        NoteBLL notebll = new NoteBLL();

        /// <summary>
        /// 实例化
        /// </summary>
        EstimateBLL esbll = new EstimateBLL();
        /// <summary>
        /// 实例化
        /// </summary>
        TopicBLL Tpbll = new TopicBLL();

        /// <summary>
        /// 实例化上下文类
        /// </summary>
        DbContextEntity db = new DbContextEntity();
        /// <summary>
        /// 实例化
        /// </summary>
        ExamBLL Eabll = new ExamBLL();
        //分页显示+查询
        public ActionResult Index(int? CollegeID, int? Cpublish, string title, string creator, int pageIndex = 1)
        {
            // int pageIndex = Convert.ToInt32(Request["page"]);
            ViewBag.CollegeID = CollegeID;
            ViewBag.Cpublish = Cpublish;
            ///判断
            ViewBag.title = title;
            ViewBag.creator = creator;

            ///判断

            int pageSize = 5;
            //int pageCount = 0;
            //int total = 0;
            //List<Interview> lst = bll.getEntityPagging(p => p.InterviewID, p => true, pageIndex, pageSize, out total, out pageCount);
            // List<Courses> clst = cbll.getEntityList(p =>true).ToList();
            List<Courses> clst = cbll.getEntityList(p => true).OrderByDescending(p => p.CreateTime).Where(p => (CollegeID == null ? true : p.CollegeId == CollegeID) && (string.IsNullOrEmpty(creator) ? true : p.CreatePeople.Contains(creator)) && (Cpublish == null ? true : p.Cpublish == Cpublish) && (string.IsNullOrEmpty(title) ? true : p.CTitle.Contains(title))).ToList();
            int Count = clst.Count(); ;
            ////总也数
            int pageCount = Count / pageSize;
            if (Count % pageSize > 0)
            {
                pageCount += 1;
            }
            clst = clst.Skip((pageIndex - 1) * (pageSize)).Take(pageSize).ToList();
            ViewBag.pageCount = pageCount;
            ViewBag.pageIndex = pageIndex;
            //ViewBag.clst = clst;
            //课程类型，学院

            List<College> lst = cobll.getEntityList(p => true);
            ViewBag.lst = lst;

            //课程推荐
            List<Courses> lstui = cbll.getEntityList(p => true).Where(p => p.TJisornot == 1).OrderByDescending(p => p.CreateTime).ToList();
            ViewBag.lstui = lstui;

            return View(clst);

        }
        //发布功能
        public ActionResult fabu(int id)
        {
            Courses cs = cbll.Search(id);
            if (cs.Cpublish == null)
            {
                cs.Cpublish = 1;

            }
            if (cs.Cpublish == 0)
            {
                cs.Cpublish = 1;

            }
            if (cs.Cpublish == 2)
            {
                cs.Cpublish = 1;
            }
            cbll.Edit(cs);
            return RedirectToAction("Index");
        }

        public ActionResult tuijian(int id)
        {
            Courses cs = cbll.Search(id);
            if (cs.TJisornot == null)
            {
                cs.TJisornot = 1;

            }
            if (cs.TJisornot == 0)
            {
                cs.TJisornot = 1;

            }

            cbll.Edit(cs);
            return RedirectToAction("Index");
        }
        //取消推荐
        public ActionResult quxiaotuijian(int id)
        {
            Courses cs = cbll.Search(id);
            if (cs.TJisornot == 1)
            {
                cs.TJisornot = 0;

            }


            cbll.Edit(cs);
            return RedirectToAction("Index");
        }
        //关闭功能
        public ActionResult guanbi(int id)
        {
            Courses cs = cbll.Search(id);

            if (cs.Cpublish == 0)
            {
                cs.Cpublish = 2;
            }
            if (cs.Cpublish == 1)
            {
                cs.Cpublish = 2;
            }
            cbll.Edit(cs);
            return RedirectToAction("Index");
        }
        //学院下拉框
        public ActionResult showcollege()
        {
            List<College> lst = cobll.getEntityList(p => true).ToList();
            return Json(lst, JsonRequestBehavior.AllowGet);
        }
        public string showtui()
        {
            int id = Convert.ToInt32(Request["id"]);
            string title = Request["title"];
            string creator = Request["creator"];
            //课程推荐
            List<Courses> lstui = cbll.getEntityList(p => true).OrderByDescending(p => p.CreateTime).Where(p => p.TJisornot == 1).ToList();
            lstui = lstui.Where(p => (string.IsNullOrEmpty(title) ? true : p.CTitle.Contains(title)) && (string.IsNullOrEmpty(creator) ? true : p.CreatePeople.Contains(creator)) && (id == 0) ? true : p.CollegeId == id).ToList();
            //List<Courses> lstui = cbll.getEntityList(p => true).OrderByDescending(p => p.CreateTime).Where(p => (p.TJisornot == 1) && (string.IsNullOrEmpty(title) ? true : p.CTitle.Contains(title)) && (string.IsNullOrEmpty(creator) ? true : p.CreatePeople.Contains(creator)) && (id == 0) ? true : p.CollegeId == id).ToList();
            var str = "";
            foreach (var item in lstui)
            {
                str += "<tr id=\"course-tr-20\" data-sort=\"111\">";

                str += "<td>" + item.CoursesCode + "</td>";
                str += "<td><a href=\"/course/20\" target=\"_blank\"><strong>" + item.CoursesName + "</strong></a><br><span class=\"text-muted text-sm\">分类：" + item.College.CollegeName + "</span></td>";
                str += " <td> <a href=\"javascript:;\"  data-toggle=\"modal\" data-target=\"#modal\" >" + item.CreatePeople + "</a>  <br> <span class=\"text-muted text-sm\">" + item.CreateTime + "</span>   </td>";

                str += "<td>" + item.TJTime + "</td>";

                str += " <td> <div class=\"btn-group\">";
                str += " <a class=\"btn btn-default btn-sm\" href='/Course/tuishezhi/" + item.CoursesId + "' data-target='#myModal' data-toggle=\"modal\" >设置序号</a><a href=\"#\" type=\"button\" class=\"btn btn-default btn-sm dropdown-toggle\" data-toggle=\"dropdown\">";

                str += "<span class=\"caret\"></span> </a> <ul class=\"dropdown-menu pull-right\"><li><a class=\"cancel-recommend-course\" href=\"javascript:\" ><span class=\"glyphicon glyphicon-hand-right\"></span> 取消推荐</a></li></ul>  </div>  </td>";

                str += " </tr>";
            }

            return str;

        }

        //模态框设置序号
        public ActionResult tuishezhi(int id)
        {

            Courses cs = cbll.Search(id);
            return View(cs);
        }

        public ActionResult tuishe(Courses cs)
        {
            int id = cs.CoursesId;
            //int num = Convert.ToInt32(Request["num"]);
            Courses css = cbll.Search(id);
            css.CoursesCode = Convert.ToInt32(Request["CoursesCode"]);
            //cs.CoursesCode = num;
            cbll.Edit(css);
            return Content("<script>;location.href='/Course/Index';</script>");
        }
        /// <summary>
        /// 课程统计
        /// </summary>
        /// <returns></returns>
        public ActionResult test()
        {
            UserInfoBLL userbll = new UserInfoBLL();
            int pageIndex = Convert.ToInt32(Request["pageIndex"]);
            int pageSize = Convert.ToInt32(Request["pageSize"]);
            string id = Request["id"] == null ? "" : Request["id"];
            string title = Request["title"] == null ? "" : Request["title"];
            string creator = Request["creator"] == null ? "" : Request["creator"];
            List<Courses> query = coursebll.getEntityList(p => true)
                .Where(p => (id == "" ? true : p.CollegeId == Convert.ToInt32(id)) && (title == "" ? true : p.CTitle.Contains(title)) && (creator == "" ? true : p.CreatePeople.Contains(creator)))
                .ToList();

            var qq = from m in query
                     select new ShowView
                     {
                         Name = m.CoursesName,
                         CouseCount = 2,
                         StudentCount = (from x in query
                                         join n in userbll.getEntityList(p => true)
                                             on x.UserInfoId equals n.UserInfoId
                                         select n).Count(),
                         Sal = m.CPrice,
                         HourCount = (from y in query
                                      join n in hourbll.getEntityList(p => true)
                                          on y.CoursesId equals n.CoursesID
                                      select n).Count()

                     };

            query = query.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            return Json(query, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CourseCreate()
        {


            return View();
        }


        /// <summary>
        /// 修改课程信息
        /// </summary>
        /// <param name="id">课程对象ID</param>
        /// <returns></returns>

        public ActionResult CourseCreateManage(int id)
        {
            if (Session["Uname"] != null)
            {
                //获取ID
				Session["Coursesid"] = id;
                //根据ID找到单个课程信息
                Courses course = coursebll.Search(id);
                //获取学院分类集合并传至页面下拉框显示
                List<College> colist = cobll.getEntityList(p => true);
                ViewBag.CollegeId = new SelectList(colist, "CollegeId", "CollegeName", course.CollegeId);
                //获取标签集合并传至页面下拉框显示
                List<Lable> lalist = lablebll.getEntityList(p => true);
                ViewBag.LableId = new SelectList(lalist, "LableId", "LableName", course.LableId);

                return View(course);
            }
            else
            {
                return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
            }

        }
        /// <summary>
        /// 修改课程基本信息
        /// </summary>
        /// <param name="course"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CourseCreateManage1(Courses rcourse)
        {
            //根据Session["Courseid"]查询到单个课程信息
            int id = Convert.ToInt32(Session["Coursesid"]);
            Courses course = coursebll.Search(id);
            //给单个课程赋新值        
            course.CTitle = rcourse.CTitle;  //标题
            course.CSutTitle = rcourse.CSutTitle;   //副标题
            course.CreatePeople = rcourse.CreatePeople;  //创建老师
            course.LableId = rcourse.LableId; //标签ID
            course.CBuy = rcourse.CBuy;   //是否开始课程购买
            course.CValidity = rcourse.CValidity;  //学员有效期
            course.CPrice = rcourse.CPrice;  //课程价格
            course.CState = rcourse.CState;  //连载状态
            course.CollegeId = rcourse.CollegeId;  //分类
            if (coursebll.Edit(course))
            {
                return Content("<script>alert('保存成功！');location.href='/Course/CourseDetail?id=" + id + "'</script>");
            }
            else
            {
                return Content("<script>alert('保存失败！'); location.href='/Course/CourseCreateManage=" + id + "'</script>");
            }
        }

        #region**************** 题目管理 ****************
        SelectBLL Sbll = new SelectBLL();
        JudgeBLL Jbll = new JudgeBLL();
        GapfillingBLL Gbll = new GapfillingBLL();
        RespondBLL Rbll = new RespondBLL();


        ///// <summary>
        ///// 显示题目管理界面
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult TitleManage()
        //{
        //    try
        //    {
        //        //  Session["HourId"] = new HourBLL().getEntity(s => s.CoursesID == Convert.ToInt32(Session["CollegeId"])).HourId;
        //        List<LeEdu.Web.ViewModel.SubjectView> SubList = new List<ViewModel.SubjectView>();
        //        ViewModel.SubjectView sub = new ViewModel.SubjectView();
        //        List<Select> SelectList = Sbll.getEntityList(s => true);
        //        List<Judge> JudgeList = Jbll.getEntityList(j => true);
        //        List<GapFilling> GapFillingList = Gbll.getEntityList(g => true);
        //        List<Respond> RespondList = Rbll.getEntityList(r => true);
        //        ViewBag.SelectList = SelectList;
        //        ViewBag.JudgeList = JudgeList;
        //        ViewBag.GapFillingList = GapFillingList;
        //        ViewBag.RespondList = RespondList;

        ///// <summary>
        ///// 显示题目管理界面
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult TitleManage()
        //{
        //    try
        //    {
        //        //  Session["HourId"] = new HourBLL().getEntity(s => s.CoursesID == Convert.ToInt32(Session["CollegeId"])).HourId;
        //        List<LeEdu.Web.ViewModel.SubjectView> SubList = new List<ViewModel.SubjectView>();
        //        ViewModel.SubjectView sub = new ViewModel.SubjectView();
        //        List<Select> SelectList = Sbll.getEntityList(s => true);
        //        List<Judge> JudgeList = Jbll.getEntityList(j => true);
        //        List<GapFilling> GapFillingList = Gbll.getEntityList(g => true);
        //        List<Respond> RespondList = Rbll.getEntityList(r => true);
        //        ViewBag.SelectList = SelectList;
        //        ViewBag.JudgeList = JudgeList;
        //        ViewBag.GapFillingList = GapFillingList;
        //        ViewBag.RespondList = RespondList;



        HourBLL Hbll = new HourBLL();

        /// <summary>
        /// 显示题目管理界面
        /// </summary>
        /// <returns></returns>
        public ActionResult TitleManage(int id,string QType, int pageIndex = 1, int pageSize = 6)
        {
        
            try
            {
				int Cid = id;
				Session["Coursesid"] = id;  //绑定课程编号
                Session["CoursesCSutTitle"] = cbll.Search(id).CSutTitle;
                Session["CoursesCreatePeople"] = cbll.Search(id).CreatePeople;
                
                Session["CoursesCImage"] = cbll.Search(id).CImage;
                if (Cid == 0)
                {
                    return Content("<script>alert('您还没有课程，不能管理题目，请添加！'); location.href='/Course/HourManage/?id=" + Cid + "' </script>");
                }
                //if (Hbll.getEntity(s => s.CoursesID == Cid) == null)
                //{
                //    return Content("<script>alert('您还没有本课时，不能管理题目，请添加！'); location.href='/Course/HourManage/?id=" + Cid + "' </script>");
                //}
                //int Hid = Hbll.getEntity(s => s.CoursesID == Cid).HourId;
                // Session["HourId"] = Hid;
				//List<Select> SelectList = new List<Select>();
				//List<Judge> JudgeList = new List<Judge>();
				//List<GapFilling> GapFillingList = new List<GapFilling>();
				//List<Respond> RespondList = new List<Respond>();
				//if (QType == "选择题")
				//{
				//	SelectList = Sbll.getEntityList(s => s.CoursesId == Cid);
				//}
				//else if (QType == "判断题")
				//{
				//	JudgeList = Jbll.getEntityList(j => j.CoursesId == Cid);
				//}
				//else if (QType == "填空题")
				//{
				//	GapFillingList = Gbll.getEntityList(g => g.CoursesId == Cid);
				//}
				//else if (QType == "问答题")
				//{
				//	RespondList = Rbll.getEntityList(r => r.CoursesId == Cid);
				//}
				//else
				//{
				//	SelectList = Sbll.getEntityList(s => s.CoursesId == Cid);
				//	JudgeList = Jbll.getEntityList(j => j.CoursesId == Cid);
				//	GapFillingList = Gbll.getEntityList(g => g.CoursesId == Cid);
				//	RespondList = Rbll.getEntityList(r => r.CoursesId == Cid);
				//}

				//ViewBag.SelectList = SelectList;
				//ViewBag.JudgeList = JudgeList;
				//ViewBag.GapFillingList = GapFillingList;
				//ViewBag.RespondList = RespondList;


                //获取判断题，选择题，填空题，问答题的总数

				ViewBag.Count = qservice.GetQuestionCount();
                //当前页面
                ViewBag.pageIndex = pageIndex;
                //当前页面显示的条数
                ViewBag.pageSize = pageSize;



				ViewBag.SelectList = qservice.GetAllQuestion(id);

                return View("TitleManage");
            }
            catch (Exception)
            {

                //ViewBag.Count = Sbll.getEntityList(s => true).Count + Jbll.getEntityList(j => true).Count + Gbll.getEntityList(g => true).Count + Rbll.getEntityList(r => true).Count;
                return View();
            }
        }
        //}
        /// <summary>
        /// 根据题型找到相对应的表，根据编号删除信息 
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="Ttype">题型</param>
        /// <returns></returns>
        public ActionResult DELTitle(int id, string Ttype)
        {
            try
            {
                if (Session["Uname"] != null)
                {
					//if (Sbll.Search(id) != null && Sbll.Search(id).Genre == Ttype)
					//{
					//	Sbll.Del(Sbll.Search(id));
					//	return Content("<script>alert('删除成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
					//}
					//else if (Jbll.Search(id) != null && Jbll.Search(id).Genre == Ttype)
					//{
					//	Jbll.Del(Jbll.Search(id));
					//	return Content("<script>alert('删除成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
					//}
					//else if (Gbll.Search(id) != null && Gbll.Search(id).Genre == Ttype)
					//{
					//	Gbll.Del(Gbll.Search(id));
					//	return Content("<script>alert('删除成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
					//}
					//else if (Rbll.Search(id) != null && Rbll.Search(id).Genre == Ttype)
					//{
					//	Rbll.Del(Rbll.Search(id));
					//	return Content("<script>alert('删除成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
					//}

					//使用Dapper删除
					if (qservice.Del(id)) {
						return Content("<script>alert('删除成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
					}
                    else
                    {
						return Content("<script>alert('删除失败！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据题型找到相对应的表，根据编号编辑信息 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Ttype"></param>
        /// <returns></returns>
        public ActionResult EditTitle(int id, string Ttype)
        {
            try
            {
                if (Session["Uname"] != null)
                {
                    Session["TMid"] = id;
                    if (Sbll.Search(id) != null && Sbll.Search(id).Genre == Ttype)
                    {
                        return RedirectToAction("EditSelect");
                    }
                    else if (Jbll.Search(id) != null && Jbll.Search(id).Genre == Ttype)
                    {
                        return RedirectToAction("EditJudge");
                    }
                    else if (Gbll.Search(id) != null && Gbll.Search(id).Genre == Ttype)
                    {
                        return RedirectToAction("EditGapFilling");
                    }
                    else if (Rbll.Search(id) != null && Rbll.Search(id).Genre == Ttype)
                    {
                        return RedirectToAction("EditRespond");
                    }
                    else
                    {
						return Content("<script>alert('亲、出现意外了啊，请检查网络！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "' </script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加选择题界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSelect()
        {			
            return View();
        }

        //保存试题
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddSelTo(FormCollection Col)
        {
            try
             {

                if (Session["Uname"] != null)
                {
                

                    Select select = new Select();
					select.CoursesId = Convert.ToInt32(Session["Coursesid"]);

                    select.UpLoader = Session["Uname"].ToString();
                    select.UpTime = DateTime.Now;
                    select.Genre = "选择题";

                    select.Choice = Convert.ToInt32(Col["Choice"]);
                    select.Difficulty = Convert.ToInt32(Col["Difficulty"]);
                    select.Analysis = Col["Analysis"];
                    select.SelectA = Col["SelectA"];
                    select.SelectB = Col["SelectB"];
                    select.SelectC = Col["SelectC"];
                    select.SelectD = Col["SelectD"];
                    select.Stem = Col["Stem"];
                    select.Value = Convert.ToInt32(Col["Value"]);
                    if (select.Choice == 0)
                    {
                        select.Correct = Col["Correct"];
                        if (select.Correct.Length == 1)
                        {
                            if (Sbll.AddEntity(select))
                            {
								return Content("<script>alert('添加选择提成功，你添加的是单选！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                            }
                            else
                            {
								return Content("<script>alert('单选题答案只有一个哦，添加失败！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                            }
                        }
                        else
                        {
							return Content("<script>alert('单选题答案只有一个哦！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                        }
                    }
                    else
                    {


                        select.Correct = Col["Correct"];
                        if (select.Correct.Length < 0 && select.Correct.Length > 4)
                        {
							return Content("<script>alert('至少给一个答案吧哦！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                        }
                        else
                        {
                            if (Sbll.AddEntity(select))
                            {
								return Content("<script>alert('添加选择提成功，你添加的是多选！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                            }
                            else
                            {
                                return Content("<script>alert('至少给一个答案吧哦,添加失败！'); location.href='/Course/TitleManage'</script>");
                            }
                        }
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加判断题界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddJudge()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddJudTo(Judge judge)
        {
            try
            {
                //获取当前课程的Id
                //   Session["HourId"]= new HourBLL().getEntity(s=>s.CoursesID == Convert.ToInt32(Session["CollegeId"])).HourId;
                if (Session["Uname"] != null)
                {
					judge.CoursesId = Convert.ToInt32(Session["Coursesid"]);
                    judge.UpLoader = Session["Uname"].ToString();
                    judge.UpTime = DateTime.Now;
                    judge.Genre = "判断题";
                    if (Jbll.AddEntity(judge))
                    {
						return Content("<script>alert('添加判断题成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('添加判断题失败,请重新添加！'); location.href='/Course/AddJudge'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

       

        /// <summary>
        /// 添加填空题界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddGapfilling()
        {		
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddGapTo(GapFilling Gap)
        {
            try
            {
                if (Session["Uname"] != null)
                {
					Gap.CoursesId = Convert.ToInt32(Session["Coursesid"]);
                    Gap.UpLoader = Session["Uname"].ToString();
                    Gap.UpTime = DateTime.Now;
                    Gap.Genre = "填空题";
                    if (Gbll.AddEntity(Gap))
                    {
						return Content("<script>alert('添加填空题成功！'); location.href='/Course/TitleManage/?id=" + Session["Coursesid"] + "'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('添加填空题失败,请重新添加！'); location.href='/Course/AddGapfilling'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加问答题界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddRespond()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddRpd(Respond Rpd)
        {
            try
            {
                if (Session["Uname"] != null)
                {




					Rpd.CoursesId = Convert.ToInt32(Session["Coursesid"]);

                    Rpd.UpLoader = Session["Uname"].ToString();
                    Rpd.UpTime = DateTime.Now;
                    Rpd.Genre = "问答题";
                    if (Rbll.AddEntity(Rpd))
                    {
						return Content("<script>alert('添加问答题成功！'); location.href='/Course/TitleManage?id=" + Session["Coursesid"] + "'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('添加问答题失败,请重新添加！'); location.href='/Course/AddGapfilling'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据编号修改选择题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditSelect(int id = 0)
        {
            id = Convert.ToInt32(Session["TMid"]);
            if (id == 0)
            {
                return Content("<script>alert('Fuck！'); location.href='/Course/TitleManage'</script>");
            }
            else
            {
                return View(Sbll.Search(id));
            }
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditSelTo(FormCollection Col)
        {
            try
            {
                if (Session["Uname"] != null)
                {
                    Select select = new Select();
                    select.SelectId = Convert.ToInt32(Col["SelectId"]);
                    select.CoursesId = Convert.ToInt32(Session["Courseid"]);
                    select.UpLoader = Session["Uname"].ToString();
                    select.UpTime = DateTime.Now;
                    select.Genre = "选择题";

                    select.Choice = Convert.ToInt32(Col["Choice"]);
                    select.Difficulty = Convert.ToInt32(Col["Difficulty"]);
                    select.Analysis = Col["Analysis"];
                    select.SelectA = Col["SelectA"];
                    select.SelectB = Col["SelectB"];
                    select.SelectC = Col["SelectC"];
                    select.SelectD = Col["SelectD"];
                    select.Stem = Col["Stem"];
                    select.Value = Convert.ToInt32(Col["Value"]);
                    if (select.Choice == 0)
                    {
                        select.Correct = Col["Correct"];
                        if (select.Correct.Length == 1)
                        {
                            if (Sbll.Edit(select))
                            {
                                return Content("<script>alert('单选题修改成功！'); location.href='/Course/TitleManage'</script>");
                            }
                            else
                            {
                                return Content("<script>alert('单选题答案只有一个哦，修改失败！'); location.href='/Course/TitleManage'</script>");
                            }
                        }
                        else
                        {
                            return Content("<script>alert('单选题答案只有一个哦！'); location.href='/Course/TitleManage'</script>");
                        }
                    }
                    else
                    {


                        select.Correct = Col["Correct"];
                        if (select.Correct.Length < 0 && select.Correct.Length > 4)
                        {
                            return Content("<script>alert('至少给一个答案吧哦！'); location.href='/Course/TitleManage'</script>");
                        }
                        else
                        {
                            if (Sbll.Edit(select))
                            {
                                return Content("<script>alert('多选题修改成功！'); location.href='/Course/TitleManage'</script>");
                            }
                            else
                            {
                                return Content("<script>alert('至少给一个答案吧哦,修改失败！'); location.href='/Course/TitleManage'</script>");
                            }
                        }
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据编号修改判断题
        /// </summary>
        /// <returns></returns>
        public ActionResult EditJudge(int id = 0)
        {
            id = Convert.ToInt32(Session["TMid"]);
            return View(Jbll.Search(id));
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditJudTO(Judge judge)
        {
            try
            {
                if (Session["Uname"] != null)
                {
                    judge.JudgeId = Convert.ToInt32(Request["JudgeId"]);
                    judge.CoursesId = Convert.ToInt32(Session["Courseid"]);
                    judge.UpLoader = Session["Uname"].ToString();
                    judge.UpTime = DateTime.Now;
                    judge.Genre = "判断题";
                    if (Jbll.Edit(judge))
                    {
                        return Content("<script>alert('修改判断题成功！'); location.href='/Course/TitleManage'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('呀！ 修改失败啦！'); location.href='/Course/TitleManage'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据编号修改填空题
        /// </summary>
        /// <returns></returns>
        public ActionResult EditGapFilling(int id = 0)
        {
            id = Convert.ToInt32(Session["TMid"]);
            return View(Gbll.Search(id));
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditGapTO(GapFilling Gap)
        {
            try
            {
                if (Session["Uname"] != null)
                {
                    Gap.GapFillingId = Convert.ToInt32(Request["GapFillingId"]);
                    Gap.CoursesId = Convert.ToInt32(Session["Courseid"]);
                    Gap.UpLoader = Session["Uname"].ToString();
                    Gap.UpTime = DateTime.Now;
                    Gap.Genre = "填空题";
                    if (Gbll.Edit(Gap))
                    {
                        return Content("<script>alert('修改填空题成功！'); location.href='/Course/TitleManage'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('出错啦，自己找问题所在！'); location.href='/Course/TitleManage'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据编号修改问答题
        /// </summary>
        /// <returns></returns>
        public ActionResult EditRespond(int id = 0)
        {
            id = Convert.ToInt32(Session["TMid"]);
            return View(Rbll.Search(id));
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditRpdTO(Respond Rpd)
        {
            try
            {
                if (Session["Uname"] != null)
                {
                    Rpd.RespondId = Convert.ToInt32(Request["RespondId"]);
                    Rpd.CoursesId = Convert.ToInt32(Session["Courseid"]);
                    Rpd.UpLoader = Session["Uname"].ToString();
                    Rpd.UpTime = DateTime.Now;
                    Rpd.Genre = "问答题";
                    if (Rbll.Edit(Rpd))
                    {
                        return Content("<script>alert('修改问答题成功！'); location.href='/Course/TitleManage'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('糟了个糕，网页丢了（修改失败）！'); location.href='/Course/AddGapfilling'</script>");
                    }
                }
                else
                {
                    return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion


        /// <summary>
        /// 课程详细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult CourseDetail(int id)
        {
            //根据ID获取单个课程
            Courses cs = cbll.Search(id);

            return View(cs);
        }
        /// <summary>
        /// 修改课程详细信息
        /// </summary>
        /// <param name="course"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CourseDetail(Courses rcourse)
        {
            //根据Session["Courseid"]查询到单个课程信息
            int id = Convert.ToInt32(Session["Coursesid"]);
            Courses course = coursebll.Search(id);

            //给单个课程赋新值    
            course.CAbout = rcourse.CAbout;  //课程简介
            course.CGoal = rcourse.CGoal;  //课程目标
            course.CCrowd = rcourse.CCrowd;  //课程适应人群
            if (coursebll.Edit(course))
            {
                return Content("<script>alert('保存成功！');location.href='/Course/ImageCourse?id=" + id + "'</script>");
            }
            else
            {
                return Content("<script>alert('保存失败！'); location.href='/Course/CourseDetail=" + id + "'</script>");
            }
        }
        /// <summary>
        /// 课程图片修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ImageCourse(int id)
        { 
           Courses c = cbll.Search(id);

             
            return View(c);
        }
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult AddImage( HttpPostedFileBase CImage)
        //{
        //    //根据Session["Courseid"]查询到单个课程信息
        //    int id = Convert.ToInt32(Session["Courseid"]);
        //    Courses c = coursebll.Search(id);
        //    if (CImage == null)
        //    {
        //        cbll.Edit(c);
        //        return Content("<script>;location.href='/Course/ImageCourse?id=" + c.CoursesId + "'</script>");
        //    }
        //    else
        //    {


        // course.LableId = Session["LableId"] == null ? 0 : Convert.ToInt32(Session["LableId"]);
        // course.CollegeId = Session["CollegeId"] == null ? 0 : Convert.ToInt32(Session["CollegeId"]);

        // course.LableId = Session["LableId"] == null ? 0 : Convert.ToInt32(Session["LableId"]);
        // course.CollegeId = Session["CollegeId"] == null ? 0 : Convert.ToInt32(Session["CollegeId"]);

        //        //图片上传
        //        if (CImage != null)
        //        {
        //            if (CImage.ContentLength > 0)
        //            {
        //                string FileNmae = DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(CImage.FileName);
        //                string filePath = Path.Combine(Server.MapPath("/Content/images"), FileNmae);
        //                CImage.SaveAs(filePath);
        //                c.CImage = FileNmae;
        //            }
        //        }
        //        else
        //        {
        //            c.CImage = null;
        //        }

        //        if (cbll.Edit(c))
        //        {
        //            return Content("<script>location.href='/Course/ImageCourse?id=" + id + "'</script>");

        //        }
        //        else
        //        {
        //            return Content("<script>alert('添加失败');location.href='/RoomType/Edit'</script>");
        //        }
        //    }
        //}

        /// <summary>
        /// 上传图片功能
        /// </summary>
        /// <param name="CImage"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddImage(HttpPostedFileBase CImage)
        {

            if (Session["Uname"] != null)
            {

                //根据Session["Courseid"]查询到单个课程信息
                int id = Convert.ToInt32(Session["Coursesid"]);
                Courses course = coursebll.Search(id);               
                if (CImage == null)
                {
                    return Content("<script>alert('没有图片，请上传！');location.href='/Course/ImageCourse?id=" + id + "'</script>");
                }
                else
                {                    
                    //图片上传`
                    if (CImage.ContentLength > 0)
                    {
                        //重新命名上传图片
                        string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(CImage.FileName);
                        //保存图片到物理路径
                        string filePath = Path.Combine(Server.MapPath("/Content/images"), FileName);
                        CImage.SaveAs(filePath);
                        //课程图片路径的修改
                        course.CImage = FileName;
                         Courses cc = new Courses();
                         cc.CoursesId = id;
                         cc.CoursesName = course.CoursesName;                        
                         cc.CTitle = course.CTitle;  //标题
                         cc.CSutTitle = course.CSutTitle;   //副标题
                         cc.CreatePeople = course.CreatePeople;  //创建老师
                         cc.LableId = course.LableId; //标签ID
                         cc.CBuy = course.CBuy;   //是否开始课程购买
                         cc.CValidity = course.CValidity;  //学员有效期
                         cc.CPrice = course.CPrice;  //课程价格
                         cc.CState = course.CState;  //连载状态
                         cc.CollegeId = course.CollegeId;  //分类
                         cc.CAbout = course.CAbout;  //课程简介
                         cc.CGoal = course.CGoal;  //课程目标
                         cc.CCrowd = course.CCrowd;  //课程适应人群
                         cc.CImage = course.CImage;
                         cc.UserInfoId = course.UserInfoId;
                         //course.CoursesId = Convert.ToInt32(Session["Courseid"]);
                        if (cbll.Edit(cc))

                        {
                            return Content("<script>alert('上传成功！');location.href='/Course/ImageCourse?id=" + id + "'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('上传失败');location.href='/Course/ImageCourse?id=" + id + "'</script>");
                        }
                    }
                    else
                    {
                        return Content("<script>alert('上传图片失败，请重新选择图片');location.href='/Course/ImageCourse?id=" + id + "'</script>");
                    }
                }
            }
            else
            {
                return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
            }
        }

        /// <summary>
        /// 课时管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult HourManage(int id)
        {            
            CourseBLL cbll = new CourseBLL();
            //文件
            List<Files> list = filesbll.getEntityList(p => true);
            ViewBag.list = list;
            Session["chtid"] = id;
            //章节
            ZhangJieBLL bll = new ZhangJieBLL();
            List<ZhangJie> lst = bll.getEntityList(p => true).ToList();
            ViewBag.zhang = lst;

            //显示该课程下的课时
            List<Hour> lsth = hourbll.getEntityList(p => true).Where(p => p.CoursesID == id).ToList();
            ViewBag.lsth = lsth;
            //HourBLL hbll = new HourBLL();
            //List<Hour> hlist = hbll.getEntityList(p=>true);
            //ViewBag.hour = hlist;

            ExamBLL ebll = new ExamBLL();
            List<Exam> exam = ebll.getEntityList(p => true);
            ViewBag.exam = exam;

            return View();
        }

        /// <summary>
        /// 课时添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult HourManageAdd(int ExamID,string HTitle,double HStudyTime)
        {
            Hour h = new Hour();
            h.ExamID = ExamID;
            h.HTitle = HTitle;
            h.HStudyTime = HStudyTime;
            h.CoursesID = Convert.ToInt16(Session["chtid"]);
            int a = Convert.ToInt16(Session["chtid"]);
            HourBLL hbll = new HourBLL();
            try
            {
                hbll.AddEntity(h);
                return Content("<script>alert('创建成功！');location.href='/Course/HourManage/" + a + "'</script>");
            }
            catch (Exception)
            {
                return Content("<script>alert('创建失败！');location.href='/Course/HourManage/" + a + "'</script>");
            }
        }

        /// <summary>
        /// 添加章
        /// </summary>
        /// <returns></returns>
        public ActionResult AddZhang()
        {

            return View();
        }
        [HttpPost]
        public ActionResult AddZhang(ZhangJie zj)
        {
            int id = Convert.ToInt32(Session["Courseid"]);
            Course_ZhangJieBLL czbll = new Course_ZhangJieBLL();
            ZhangJieBLL bll = new ZhangJieBLL();
            bll.AddEntity(zj);
            //向关系表中添加关系
            Course_ZhangJie cz = new Course_ZhangJie();

            int zjid = bll.getEntity(p => p.ZhangJieID == zj.ZhangJieID).ZhangJieID;
            cz.ZhangJieID = zjid;
            cz.CoursesId = id;
            czbll.AddEntity(cz);
            return Content("<script>location.href='/Course/HourManage/?id=" + id + "';</script>");
        }
        /// <summary>
        /// 添加节
        /// </summary>
        /// <returns></returns>
        public ActionResult AddJie()
        {

            return View();
        }

        [HttpPost]
        public ActionResult AddJie(ZhangJie zj)
        {
            ZhangJieBLL bll = new ZhangJieBLL();
            bll.AddEntity(zj);
            return RedirectToAction("HourManage");
        }

        //文件管理
        public ActionResult FileManage()
        {          
            List<Files> list = filesbll.getEntityList(p => true);
            ViewBag.list = list;
            return View();
        }
        //直播
        public ActionResult livecourse()
        {
            return View();
        }

        //班级
        public ActionResult classroom()
        {
            return View();
        }

        //评价
        public ActionResult review()
        {
            return View();
        }
        //分类管理
        public ActionResult category()
        {
            return View();
        }
        //标签管理
        public ActionResult tag()
        {
            LableBLL bll = new LableBLL();
            List<Lable> st = bll.getEntityList(t => true).ToList();
            ViewBag.st = st;
            return View(st);
        }
        public ActionResult tagAdd()
        {
            return View();
        }
        [HttpPost]
        public ActionResult tagAdd(Lable la)
        {
            LableBLL bll = new LableBLL();
            if (bll.AddEntity(la))
            {
                return Content("<script>alert('添加成功'); location.href='/Course/tag'</script>");
            }
            else
            {
                return Content("<script>alert('修改失败');location.href='/Course/tag'</script>");
            }

        }

        public ActionResult tagEdite(int id)
        {
            LableBLL bll = new LableBLL();
            Lable sss = bll.Search(id);
            return View(sss);
        }
        [HttpPost]
        public ActionResult tagEdite(Lable la)
        {

            LableBLL bll = new LableBLL();
            if (bll.Edit(la))
            {
                return Content("<script> location.href='/Course/tag'</script>");
            }
            else
            {
                return Content("<script>location.href='/Course/tag'</script>");
            }
        }
        public ActionResult tagEditeDel(int id)
        {
            LableBLL bll = new LableBLL();
            Lable st = bll.Search(id);
            if (bll.Del(st))
            {
                return Content("<script> location.href='/Course/tag'</script>");
            }
            else
            {
                return Content("<script> location.href='/Course/tag'</script>");
            }
        }


        /// <summary>
        /// 创建课程
        /// </summary>
        /// <param name="course">课程对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddCourse(Courses course)
        {

            if (Session["Uname"] != null)
            {
                //course.LableId = 1;
                //course.CollegeId = 1;
                course.CreatePeople = Session["Uname"].ToString();
                course.CreateTime = DateTime.Now;
                course.UserInfoId = Convert.ToInt32(Session["id"]);
                Session["time"] = course.CreateTime;
                if (coursebll.AddEntity(course))
                {
                    return Content("<script> location.href='/Course/Index'</script>");
                }
                else
                {
                    return Content("<script> location.href='/Course/CourseCreate'</script>");
                }
            }
            else
            {
                return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
            }
        }


        /// <summary>
        /// 视频上传
        /// </summary>
        /// <param name="file">上传文件</param>
        [HttpPost]
        public void Upload(HttpPostedFileBase[] file)
        {
            string path = "";
            string extname = string.Empty;//后缀
            string fullname = string.Empty;//整个文件名
            string filename = string.Empty;
            string fname = DateTime.Now.ToString("yy-MM-dd") + Path.GetExtension(file[0].FileName);
            string sname = file[0].FileName;
            Session["sname"] = sname;
            string updir = Path.Combine(Server.MapPath("/upload/iamges"), fname);
            if (Request.Files.Count > 0)
            {
                try
                {
                    for (int j = 0; j < Request.Files.Count; j++)
                    {
                        HttpPostedFileBase uploadFile = file[j];
                        int offset = Convert.ToInt32(Request["chunk"]); //当前分块
                        int total = Convert.ToInt32(Request["chunks"]);//总的分块数量           
                        var size = Request["file_size"];
                        if (total == 1)
                        {
                            if (uploadFile.ContentLength > 0)
                            {
                                if (!Directory.Exists(updir))//判读文件夹是否存在，不存在则创建
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                extname = Path.GetExtension(uploadFile.FileName);//后缀名
                                fullname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + extname;//保存的文件路径
                                path = string.Format("{0}\\{1}", updir, fullname);
                                string newpath = fname + "/" + fullname;
                                string a = string.Format("{0}\\{1}", updir, fullname);
                                string b = a.Substring(a.LastIndexOf("upload\\iamges") + 14).Replace("\\", "/");
                                Session["Url"] = b;
                                uploadFile.SaveAs(path);
                            }
                        }
                        else
                        {
                            //文件分成多块上传 
                            fullname = WriteTempFile(uploadFile, offset);
                            if (total - offset == 1)
                            {
                                if (!Directory.Exists(updir))//判读文件夹是否存在，不存在则创建
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                //如果是最后一个分块文件 ，则把文件从临时文件夹中移到上传文件夹中
                                System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
                                string oldFullName = string.Format("{0}\\{1}", updir, uploadFile.FileName);
                                path = oldFullName;

                                FileInfo oldFi = new FileInfo(oldFullName);
                                var swsize = Convert.ToDouble(fi.Length);
                                var ssize = Convert.ToDouble(swsize / 1048576).ToString("0.00");//获取文件大小
                                Session["ssize"] = ssize;
                                if (oldFi.Exists)
                                {
                                    //文件名存在则删除旧文件   
                                    oldFi.Delete();
                                }

                                fi.MoveTo(oldFullName);//文件存入上传的文件夹

                                string a = oldFullName;
                                string b = a.Substring(a.LastIndexOf("upload\\iamges") + 14).Replace("\\", "/");
                                Session["Url"] = b;
                                string tempfiles = Path.Combine(Server.MapPath("/upload/temp"), fname);



                                if (Directory.Exists(tempfiles))
                                {
                                    //删除临时文件夹
                                    Directory.Delete(tempfiles);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                    Response.Write("Message" + ex.ToString());
                }
            }
        }


        /// <summary>
        /// 分割文件
        /// </summary>
        /// <param name="uploadFile">上传文件</param>
        /// <param name="chunk"></param>
        /// <returns></returns>
        private string WriteTempFile(HttpPostedFileBase uploadFile, int chunk)
        {
            string fname = DateTime.Now.ToString("yy-MM-dd") + Path.GetExtension(uploadFile.FileName);
            string tempDir = Path.Combine(Server.MapPath("/upload/temp"), fname);//分块之后文件保存路径

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            string fullName = string.Format("{0}\\{1}", tempDir, uploadFile.FileName);//文件路径

            if (chunk == 0)
            {
                //如果是第一个分块，则直接保存（临时文件）  
                uploadFile.SaveAs(fullName);
            }
            else
            {
                //如果是其他分块文件 ，则原来的分块文件，读取流，然后文件最后写入相应的字节
                FileStream fs = new FileStream(fullName, FileMode.Append);
                if (uploadFile.ContentLength > 0)
                {
                    int FileLen = uploadFile.ContentLength;
                    byte[] input = new byte[FileLen]; // Initialize the stream.
                    System.IO.Stream MyStream = uploadFile.InputStream; // Read the file into the byte array. 
                    MyStream.Read(input, 0, FileLen);
                    fs.Write(input, 0, FileLen);
                    fs.Close();
                }
            }
            return fullName;
        }


        /// <summary>
        /// 添加课时同时向文件管理中存入数据
        /// </summary>
        /// <param name="hours">课时对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddCourseHour(Hour hours)
        {

            int id = Convert.ToInt32(Session["Coursesid"]);
            int fid = Convert.ToInt32(Request["fid"]);
            Files file = filesbll.Search(fid);
            if (file != null)
            {
                hours.HVideo = file.FUrl;
                hours.HVideoTime = 0;
                hours.HStudyTime = 0;
                hours.CoursesID = id;

                //计算课时条数
                int hcount = hourbll.getEntityList(p => true).Count();
                Session["hcount"] = hcount;
                if (hourbll.AddEntity(hours))
                {
                    return Content("<script> location.href='/Course/HourManage?id=" + id + "'</script>");
                }
                else
                {
                    return Content("<script> location.href='/Course/HourManage?id=" + id + "'</script>");
                }
            }
            else
            {
                hours.HVideoTime = 0;
                hours.HStudyTime = 0;
                hours.CoursesID = id;
                hours.HVideo = Session["Url"].ToString();
                int type = Convert.ToInt32(Request["HType"]);
                Files files = new Files();
                files.FilesName = Session["sname"].ToString();
                files.FType = type;
                files.FSize = Session["ssize"].ToString();
                files.FTime = DateTime.Now;
                files.FUrl = Session["Url"].ToString();

                //计算课时条数
                int hcount = hourbll.getEntityList(p => true).Count();
                Session["hcount"] = hcount;
                if (hourbll.AddEntity(hours))
                {
                    if (filesbll.AddEntity(files))
                    {
                        return Content("<script> location.href='/Course/HourManage?id=" + id + "'</script>");
                    }
                    else
                    {
                        return Content("<script> location.href='/Course/HourManage?id=" + id + "'</script>");
                    }
                }
                else
                {
                    return Content("<script> location.href='/Course/HourManage?id=" + id + "'</script>");
                }
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file">上传文件</param>
        [HttpPost]
        public void UploadFile(HttpPostedFileBase[] file)
        {
            string path = "";
            string extname = string.Empty;//后缀
            string fullname = string.Empty;//整个文件名
            string filename = string.Empty;
            string fname = DateTime.Now.ToString("yy-MM-dd") + Path.GetExtension(file[0].FileName);
            string wname = file[0].FileName;
            Session["filename"] = wname;
            string updir = Path.Combine(Server.MapPath("/upload/iamges"), fname);
            if (Request.Files.Count > 0)
            {
                try
                {
                    for (int j = 0; j < Request.Files.Count; j++)
                    {
                        HttpPostedFileBase uploadFile = file[j];
                        int offset = Convert.ToInt32(Request["chunk"]); //当前分块
                        int total = Convert.ToInt32(Request["chunks"]);//总的分块数量       
                        var size = Request["file_size"];
                        if (total == 1)
                        {
                            if (uploadFile.ContentLength > 0)
                            {
                                if (!Directory.Exists(updir))//判读文件夹是否存在，不存在则创建
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                extname = Path.GetExtension(uploadFile.FileName);//后缀名
                                fullname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + extname;//保存的文件路径
                                path = string.Format("{0}\\{1}", updir, fullname);
                                string newpath = fname + "/" + fullname;
                                string a = string.Format("{0}\\{1}", updir, fullname);
                                string b = a.Substring(a.LastIndexOf("upload\\iamges") + 18).Replace("\\", "/");
                                Session["Urlfile"] = b;
                                uploadFile.SaveAs(path);
                            }
                        }
                        else
                        {
                            //文件分成多块上传 
                            fullname = WriteTempFile1(uploadFile, offset);
                            if (total - offset == 1)
                            {
                                if (!Directory.Exists(updir))//判读文件夹是否存在，不存在则创建
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                //如果是最后一个分块文件 ，则把文件从临时文件夹中移到上传文件夹中
                                System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
                                string oldFullName = string.Format("{0}\\{1}", updir, uploadFile.FileName);
                                path = oldFullName;

                                FileInfo oldFi = new FileInfo(oldFullName);
                                var fwsize = Convert.ToDouble(fi.Length);
                                var wsize = Convert.ToDouble(fwsize / 1048576).ToString("0.00");//获取文件大小
                                Session["wsize"] = wsize;
                                if (oldFi.Exists)
                                {
                                    //文件名存在则删除旧文件   
                                    oldFi.Delete();
                                }
                                fi.MoveTo(oldFullName);//文件存入上传的文件夹
                                string a = oldFullName;
                                string b = a.Substring(a.LastIndexOf("upload\\iamges") + 18).Replace("\\", "/");
                                Session["Urlfile"] = b;
                                string tempfiles = Path.Combine(Server.MapPath("/upload/temp"), fname);
                                if (Directory.Exists(tempfiles))
                                {
                                    //删除临时文件夹
                                    Directory.Delete(tempfiles);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("Message" + ex.ToString());
                }
            }
        }


        /// <summary>
        /// 分割文件
        /// </summary>
        /// <param name="uploadFile">上传文件</param>
        /// <param name="chunk"></param>
        /// <returns></returns>
        private string WriteTempFile1(HttpPostedFileBase uploadFile, int chunk)
        {
            string fname = DateTime.Now.ToString("yy-MM-dd") + Path.GetExtension(uploadFile.FileName);
            string tempDir = Path.Combine(Server.MapPath("~/upload/temp"), fname);//分块之后文件保存路径

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            string fullName = string.Format("{0}\\{1}", tempDir, uploadFile.FileName);//文件路径

            if (chunk == 0)
            {
                //如果是第一个分块，则直接保存（临时文件）  
                uploadFile.SaveAs(fullName);
            }
            else
            {
                //如果是其他分块文件 ，则原来的分块文件，读取流，然后文件最后写入相应的字节
                FileStream fs = new FileStream(fullName, FileMode.Append);
                if (uploadFile.ContentLength > 0)
                {
                    int FileLen = uploadFile.ContentLength;
                    byte[] input = new byte[FileLen]; // Initialize the stream.
                    System.IO.Stream MyStream = uploadFile.InputStream; // Read the file into the byte array. 
                    MyStream.Read(input, 0, FileLen);
                    fs.Write(input, 0, FileLen);
                    fs.Close();
                }
            }
            return fullName;
        }

        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="file">文件对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddFiles(Files file)
        {
            file.FilesName = Session["filename"].ToString();
            file.FSize = Session["wsize"].ToString();
            file.FUrl = Session["Urlfile"].ToString();
            file.FTime = DateTime.Now;
            if (filesbll.AddEntity(file))
            {
                return Content("<script>alert('添加成功！！！');location.href='/Course/FileManage'</script>");
            }
            else
            {
                return Content("<script>alert('添加失败！！！');location.href='/Course/FileManage'</script>");
            }
        }


        /// <summary>
        /// 删除上传文件
        /// </summary>
        /// <returns></returns>
        public string DelFile()
        {
            BLL.FilesBLL bll = new FilesBLL();

            string[] jihe = Request["jihe"].Split(',');

            foreach (var item in jihe)
            {
                Files file = bll.Search(Convert.ToInt32(item));
                bll.Del(file);
            }

            return "1";
        }

        //笔记管理页面
        public ActionResult Notes(int? HourID, string NoteContent, int PageIndex = 1)
        {
            int PageSize = 5;

            int Count = notebll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(NoteContent) ? true : t.NoteContent.Contains(NoteContent)) && (HourID == null ? true : t.HourId == HourID)).Count();
            //int Count = notebll.getEntityList(t => (string.IsNullOrEmpty(NoteContent) ? true : t.NoteContent.Contains(NoteContent)) && (HourID == null) ? true : t.HourId == HourID).Count();
            int PageCount = Count / PageSize;

            if (Count % PageSize != 0)
            {
                PageCount += 1;
            }

            if (PageIndex < 0)
            {
                PageIndex = 1;
            }

            if (PageIndex > PageCount)
            {
                PageIndex = PageCount;
            }

            ViewBag.PageIndex = PageIndex;
            ViewBag.PageSize = PageSize;
            ViewBag.Count = Count;
            ViewBag.PageCount = PageCount;
            ViewBag.NoteContent = NoteContent;
            ViewBag.HourID = HourID;
            List<Note> note = notebll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(NoteContent) ? true : t.NoteContent.Contains(NoteContent)) && (HourID == null ? true : t.HourId == HourID)).Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList();
            return View(note);
        }
        //删除笔记
        public ActionResult DelNotes(int id)
        {
            bool s = notebll.Del(notebll.getEntity(t => t.ID == id));
            if (s)
            {
                return RedirectToAction("Notes");
            }
            else
            {
                return Content("<script>alert('删除失败');location.href='/Course/Notes'</script>");
            }
        }
        //批量删除笔记
        public ActionResult PLDel()
        {
            string a = Request["id"];
            string[] aa = a.Split(',');

            foreach (var item in aa)
            {
                notebll.Del(notebll.Search(Convert.ToInt32(item)));
            }
            return Content("1");
        }
        //评论管理页面
        public ActionResult Estimate(int? Score, int? CoursesID, string EstimateContent, int PageIndex = 1)
        {
            int PageSize = 5;
            int Count = esbll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(EstimateContent) ? true : t.EstimateContent.Contains(EstimateContent)) && ((CoursesID == null) ? true : t.CoursesID == CoursesID) && ((Score == null) ? true : t.Score == Score)).Count();
            int PageCount = Count / PageSize;

            if (Count % PageSize != 0)
            {
                PageCount += 1;
            }

            if (PageIndex < 0)
            {
                PageIndex = 1;
            }

            if (PageIndex > PageCount)
            {
                PageIndex = PageCount;
            }

            ViewBag.PageIndex = PageIndex;
            ViewBag.PageSize = PageSize;
            ViewBag.Count = Count;
            ViewBag.PageCount = PageCount;
            ViewBag.Score = Score;
            ViewBag.CoursesID = CoursesID;
            ViewBag.EstimateContent = EstimateContent;

            List<Estimate> es = esbll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(EstimateContent) ? true : t.EstimateContent.Contains(EstimateContent)) && ((CoursesID == null) ? true : t.CoursesID == CoursesID) && ((Score == null) ? true : t.Score == Score)).Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList();
            return View(es);
        }
        //删除评论
        public ActionResult DelEstimate(int id)
        {
            bool s = esbll.Del(esbll.getEntity(t => t.ID == id));
            if (s)
            {
                return RedirectToAction("Estimate");
            }
            else
            {
                return Content("<script>alert('删除失败');location.href='/Course/Estimate'</script>");
            }
        }
        //批量删除评论
        public ActionResult PLDelEstimate()
        {
            string a = Request["id"];
            string[] aa = a.Split(',');

            foreach (var item in aa)
            {
                esbll.Del(esbll.Search(Convert.ToInt32(item)));
            }
            return Content("1");
        }
        //话题
        public ActionResult ShowTopic(string TopicTitle, int? UserInfoId, int? Attribute, int PageIndex = 1)
        {
            int PageSize = 5;
            int Count = Tpbll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(TopicTitle) ? true : t.TopicTitle.Contains(TopicTitle)) && ((UserInfoId == null) ? true : t.UserInfoId == UserInfoId) && ((Attribute == null) ? true : t.Attribute == Attribute) && (t.TId == 0)).Count();
            int PageCount = Count / PageSize;

            if (Count % PageSize != 0)
            {
                PageCount += 1;
            }

            if (PageIndex < 0)
            {
                PageIndex = 1;
            }

            if (PageIndex > PageCount)
            {
                PageIndex = PageCount;
            }

            ViewBag.PageIndex = PageIndex;
            ViewBag.PageSize = PageSize;
            ViewBag.Count = Count;
            ViewBag.PageCount = PageCount;
            ViewBag.TopicTitle = TopicTitle;
            ViewBag.UserInfoId = UserInfoId;
            ViewBag.Attribute = Attribute;

            List<Topic> es = Tpbll.getEntityList(t => true).Where(t => (string.IsNullOrEmpty(TopicTitle) ? true : t.TopicTitle.Contains(TopicTitle)) && ((UserInfoId == null) ? true : t.UserInfoId == UserInfoId) && ((Attribute == null) ? true : t.Attribute == Attribute) && (t.TId == 0)).Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList();
            return View(es);


        }
        //删除
        public ActionResult DelTp(int id)
        {
            bool s = Tpbll.Del(Tpbll.getEntity(t => t.ID == id));
            if (s)
            {
                List<Topic> tp = Tpbll.getEntityList(t => true).Where(t => t.TId == id).ToList();
                foreach (var item in tp)
                {
                    Tpbll.Del(item);
                }
                //Tpbll.Del();
                return RedirectToAction("ShowTopic");
            }
            else
            {
                return Content("<script>alert('删除失败');location.href='/Course/ShowTopic'</script>");
            }
        }
        //批量删除话题
        public ActionResult PLDelTp()
        {
            string a = Request["id"];
            string[] aa = a.Split(',');

            foreach (var item in aa)
            {
                Tpbll.Del(Tpbll.Search(Convert.ToInt32(item)));
            }
            return Content("1");
        }

        public ActionResult DzNotes(int id)
        {
            Topic kk = Tpbll.getEntityList(p => true).Where(p => p.ID == id).FirstOrDefault();

            if (kk.Attribute == 1)
            {
                kk.Attribute = 2;
            }
            else { kk.Attribute = 1; }
            if (Tpbll.Edit(kk))
            {

                return RedirectToAction("ShowTopic");
            }
            else
            {
                return Content("0");
            }

        }

        /// <summary>
        /// 试卷管理
        /// </summary>
        /// <returns></returns>
        public ActionResult CourseExam()
        {
            return View();
        }

        /// <summary>
        /// 批阅试卷
        /// </summary>
        /// <returns></returns>
        public ActionResult ReadoverExam()
        {
            List<Exam> lst = Eabll.getEntityList(p => true).Where(p => p.ReadState == 0).ToList();
            return View(lst);
        }

        /// <summary>
        /// 已批阅
        /// </summary>
        /// <returns></returns>
        public ActionResult Finished()
        {
            List<Exam> lst = Eabll.getEntityList(p => true).Where(p => p.ReadState == 1).ToList();
            return View(lst);
        }

        /// <summary>
        /// 创建试卷页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Exam()
        {
            #region 创建试卷页面
            SelectBLL sbll = new SelectBLL();
            GapfillingBLL gbll = new GapfillingBLL();
            JudgeBLL jbll = new JudgeBLL();
            RespondBLL rbll = new RespondBLL();
            //单选题个数
            int ssum = sbll.getEntityList(p => true).Where(p => p.Choice == 0).Count();
            ViewData["ssum"] = ssum;
            //多选个数
            int dsum = sbll.getEntityList(p => true).Where(p => p.Choice == 1).Count();
            ViewData["dsum"] = dsum;
            //填空个数
            int gsum = gbll.getEntityList(p => true).Count();
            ViewData["gsum"] = gsum;
            //判断个数
            int jsum = jbll.getEntityList(p => true).Count();
            ViewData["jsum"] = jsum;
            //问答个数
            int rsum = rbll.getEntityList(p => true).Count();
            ViewData["rsum"] = rsum;


            return View();
            #endregion
        }

        /// <summary>
        /// 查看试卷
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckExam(int id)
        {

            return View(Eabll.getEntity(p => p.ExamID == id));
        
        }
        /// <summary>
        /// 完成批阅
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FinishedRead(int id)
        {

            Exam ea = Eabll.getEntity(p => p.ExamID == id);
            ea.ReadState = 1;

            try
            {
                Eabll.Edit(ea);
                return Content("<script>alert('已批阅成功') location.href('/Course/Finished')</script>");
            }
            catch (Exception)
            {

                return View();
            }


        }

        /// <summary>
        /// 价格设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CoursePrice(int id)
        {
            if (Session["Uname"] != null)
            {
                //获取ID
                Session["Courseid"] = id;
                //根据ID找到单个课程信息
                Courses course = coursebll.Search(id);
                return View(course);
            }
            else
            {
                return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
            }
        }

        /// <summary>
        /// 创建试卷点击保存下一步操作
        /// </summary>
        /// <returns></returns>
        public ActionResult Examsc(int sdxsum, int ddxsum, int gtksum, int jpdsum, int rwdsum,
            int d1, int d2, int g1, int j1, int r1, string ExamName, string Description, int LimitedTime, int Mode, int? q)
        {
            #region 验证


            SelectBLL sbll = new SelectBLL();
            GapfillingBLL gbll = new GapfillingBLL();
            JudgeBLL jbll = new JudgeBLL();
            RespondBLL rbll = new RespondBLL();
            if (sdxsum > Convert.ToInt32(sbll.getEntityList(p => true).Where(p => p.Choice == 0).Count()))
            {
                return Content("<script>alert('单选题大于总题数了！');location.href='/Course/Exam'</script>");
            }
            else if (Convert.ToInt32(sbll.getEntityList(p => true).Where(p => p.Choice == 1).Count()) < ddxsum)
            {
                return Content("<script>alert('多选题大于总题数了！');location.href='/Course/Exam'</script>");
            }
            else if (Convert.ToInt32(gbll.getEntityList(p => true).Count()) < gtksum)
            {
                return Content("<script>alert('填空题大于总题数了！');location.href='/Course/Exam'</script>");
            }
            else if (Convert.ToInt32(jbll.getEntityList(p => true).Count()) < jpdsum)
            {
                return Content("<script>alert('判断题大于总题数了！');location.href='/Course/Exam'</script>");
            }
            else if (Convert.ToInt32(rbll.getEntityList(p => true).Count()) < rwdsum)
            {
                return Content("<script>alert('问答题大于总题数了！');location.href='/Course/Exam'</script>");
            }
            #endregion

            #region  给试卷赋值
            Exam c = new MODEL.Exam();
            //试卷名称
            c.ExamName = ExamName;
            //试卷描述
            c.Description = Description;
            //时间限制
            c.LimitedTime = LimitedTime;
            //生成方式
            c.Mode = Mode;
            //发布状态
            c.PubState = 0;
            //添加人
            c.UserInfoId = Convert.ToInt32(Session["id"]);
            //所属课程
            c.CoursesId = Convert.ToInt16(Session["Courseid"]);
            //发布时间
            c.PubTime = DateTime.Now;
            //单选积分
            c.singchoiceScore = d1;
            //多选积分
            c.ChoiceScore = d2;
            //填空积分
            c.FillingScore = g1;
            //判断积分
            c.JudgeScore = j1;
            //问答积分
            c.SketchScore = r1;
            #endregion

            #region 随机数生成所有题
            Random r = new Random();
            if (Mode == 1)
            {
                #region 获取所有单选题ID
                if (sdxsum == 0)
                {
                    c.SingleChoiceID = null;
                }
                else
                {
                    List<Select> list = sbll.getEntityList(p => true).Where(p => p.Choice == 0).ToList();

                    int[] num = new int[sdxsum];
                    for (int i = 0; i < sdxsum; i++)
                    {
                        var n = r.Next(0, list.Count);
                        if (!num.Contains(n))
                        {
                            num[i] = n;
                        }
                    }
                    foreach (var a in num)
                    {
                        string id = list[a].SelectId.ToString() + ",";
                        c.SingleChoiceID += id;
                    }
                    c.SingleChoiceID = c.SingleChoiceID.Substring(0, c.SingleChoiceID.Length - 1);
                }
                #endregion

                #region 获取所有多选题ID
                if (ddxsum == 0)
                {
                    c.ChoiceID = null;
                }
                else
                {
                    List<Select> list1 = sbll.getEntityList(p => true).Where(p => p.Choice == 1).ToList();
                    int[] num1 = new int[ddxsum];
                    for (int i = 0; i < ddxsum; i++)
                    {
                        var n = r.Next(0, list1.Count);
                        if (!num1.Contains(n))
                        {
                            num1[i] = n;
                        }
                    }
                    foreach (var a in num1)
                    {
                        string id = list1[a].SelectId.ToString() + ",";
                        c.ChoiceID += id;
                    }
                    c.ChoiceID = c.ChoiceID.Substring(0, c.ChoiceID.Length - 1);
                }
                #endregion

                #region 获取所有填空题ID
                if (gtksum == 0)
                {
                    c.FillingID = null;
                }
                else
                {
                    List<GapFilling> list2 = gbll.getEntityList(p => true);
                    int[] num2 = new int[gtksum];
                    for (int i = 0; i < gtksum; i++)
                    {
                        var n = r.Next(0, list2.Count);
                        if (!num2.Contains(n))
                        {
                            num2[i] = n;
                        }
                    }
                    foreach (var a in num2)
                    {
                        string id = list2[a].GapFillingId.ToString() + ",";
                        c.FillingID += id;
                    }
                    c.FillingID = c.FillingID.Substring(0, c.FillingID.Length - 1);
                }

                #endregion

                #region 获取所有判断ID
                if (jpdsum == 0)
                {
                    c.JudgeID = null;
                }
                else
                {
                    List<Judge> list3 = jbll.getEntityList(p => true);
                    int[] num3 = new int[jpdsum];
                    for (int i = 0; i < jpdsum; i++)
                    {
                        var n = r.Next(0, list3.Count);
                        if (!num3.Contains(n))
                        {
                            num3[i] = n;
                        }
                    }
                    foreach (var a in num3)
                    {
                        string id = list3[a].JudgeId.ToString() + ",";
                        c.JudgeID += id;
                    }
                    c.JudgeID = c.JudgeID.Substring(0, c.JudgeID.Length - 1);
                }

                #endregion

                #region 获取所有问答题ID
                if (rwdsum == 0)
                {
                    c.SketchID = null;
                }
                else
                {
                    List<Respond> list4 = rbll.getEntityList(p => true);
                    int[] num4 = new int[rwdsum];
                    for (int i = 0; i < rwdsum; i++)
                    {
                        var n = r.Next(0, list4.Count);
                        if (!num4.Contains(n))
                        {
                            num4[i] = n;
                        }
                    }
                    foreach (var a in num4)
                    {
                        string id = list4[a].RespondId.ToString() + ",";
                        c.SketchID += id;
                    }
                    c.SketchID = c.SketchID.Substring(0, c.SketchID.Length - 1);
                }

                #endregion

                c.Score = sdxsum * d1 + ddxsum * d2 + gtksum * g1 + jpdsum * j1 + rwdsum * r1;
                c.queber = sdxsum + ddxsum + gtksum + jpdsum + rwdsum;
                
                ExamBLL bll = new ExamBLL();
                try
                {
                    bll.AddEntity(c);
                    return Content("<script>alert('创建成功！');location.href='/Course/Exammba'</script>");
                }
                catch (Exception)
                {
                    return Content("<script>alert('创建失败！');location.href='/Course/Exammba'</script>");
                }
            }
            #endregion

            #region 判断难度生成
            else
            {
                #region 简单难度
                if (q == 1)
                {
                    if (ddxsum == 0)
                    {
                        c.SingleChoiceID = null;
                    }
                    else
                    {
                        //简单单选题
                        List<Select> jd1 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 1 && p.Choice == 0).ToList();
                        foreach (var a in jd1)
                        {
                            c.SingleChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.SingleChoiceID = c.SingleChoiceID.Substring(0, c.SingleChoiceID.Length - 1);
                    }

                    //简单多选题
                    if (ddxsum == 0)
                    {
                        c.ChoiceID = null;
                    }
                    else
                    {
                        List<Select> jd2 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 1 && p.Choice == 1).ToList();
                        foreach (var a in jd2)
                        {
                            c.ChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.ChoiceID = c.ChoiceID.Substring(0, c.ChoiceID.Length - 1);
                    }

                    //简单填空题
                    if (ddxsum == 0)
                    {
                        c.FillingID = null;
                    }
                    else
                    {
                        List<GapFilling> tk = gbll.getEntityList(p => true).Where(p => p.Difficulty == 1).ToList();
                        foreach (var a in tk)
                        {
                            c.FillingID += a.GapFillingId.ToString() + ",";
                        }
                        c.FillingID = c.FillingID.Substring(0, c.FillingID.Length - 1);
                    }

                    //简单判断题
                    if (ddxsum == 0)
                    {
                        c.JudgeID = null;
                    }
                    else
                    {
                        List<Judge> jdpd = jbll.getEntityList(p => true).Where(p => p.Difficulty == 1).ToList();
                        foreach (var a in jdpd)
                        {
                            c.JudgeID += a.JudgeId.ToString() + ",";
                        }
                        c.JudgeID = c.JudgeID.Substring(0, c.JudgeID.Length - 1);
                    }

                    //简单问答题
                    if (ddxsum == 0)
                    {
                        c.SketchID = null;
                    }
                    else
                    {
                        List<Respond> jdwd = rbll.getEntityList(p => true).Where(p => p.Difficulty == 1).ToList();
                        foreach (var a in jdwd)
                        {
                            c.SketchID += a.RespondId.ToString() + ",";
                        }
                        c.SketchID = c.SketchID.Substring(0, c.SketchID.Length - 1);
                    }

                    c.Score = sdxsum * d1 + ddxsum * d2 + gtksum * g1 + jpdsum * j1 + rwdsum * r1;
                    c.queber = sdxsum + ddxsum + gtksum + jpdsum + rwdsum;
                    ExamBLL bll = new ExamBLL();
                    try
                    {
                        bll.AddEntity(c);
                        return Content("<script>alert('创建成功！');location.href='/Course/Exammba'</script>");
                    }
                    catch (Exception)
                    {
                        return Content("<script>alert('创建失败！');location.href='/Course/Exammba'</script>");
                    }
                }
                #endregion

                #region 中等难度
                else if (q == 2)
                {
                    //中等单选题
                    if (ddxsum == 0)
                    {
                        c.SingleChoiceID = null;
                    }
                    else
                    {
                        List<Select> jd1 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 2 && p.Choice == 0).ToList();
                        foreach (var a in jd1)
                        {
                            c.SingleChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.SingleChoiceID = c.SingleChoiceID.Substring(0, c.SingleChoiceID.Length - 1);
                    }

                    //中等多选题
                    if (ddxsum == 0)
                    {
                        c.ChoiceID = null;
                    }
                    else
                    {
                        List<Select> jd2 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 2 && p.Choice == 1).ToList();
                        foreach (var a in jd2)
                        {
                            c.ChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.ChoiceID = c.ChoiceID.Substring(0, c.ChoiceID.Length - 1);
                    }

                    //中等填空题
                    if (ddxsum == 0)
                    {
                        c.FillingID = null;
                    }
                    else
                    {
                        List<GapFilling> tk = gbll.getEntityList(p => true).Where(p => p.Difficulty == 2).ToList();
                        foreach (var a in tk)
                        {
                            c.FillingID += a.GapFillingId.ToString() + ",";
                        }
                        c.FillingID = c.FillingID.Substring(0, c.FillingID.Length - 1);
                    }

                    //中等判断题
                    if (ddxsum == 0)
                    {
                        c.JudgeID = null;
                    }
                    else
                    {
                        List<Judge> jdpd = jbll.getEntityList(p => true).Where(p => p.Difficulty == 2).ToList();
                        foreach (var a in jdpd)
                        {
                            c.JudgeID += a.JudgeId.ToString() + ",";
                        }
                        c.JudgeID = c.JudgeID.Substring(0, c.JudgeID.Length - 1);
                    }

                    //中等问答题
                    if (ddxsum == 0)
                    {
                        c.SketchID = null;
                    }
                    else
                    {
                        List<Respond> jdwd = rbll.getEntityList(p => true).Where(p => p.Difficulty == 2).ToList();
                        foreach (var a in jdwd)
                        {
                            c.SketchID += a.RespondId.ToString() + ",";
                        }
                        c.SketchID = c.SketchID.Substring(0, c.SketchID.Length - 1);
                    }

                    c.Score = sdxsum * d1 + ddxsum * d2 + gtksum * g1 + jpdsum * j1 + rwdsum * r1;
                    c.queber = sdxsum + ddxsum + gtksum + jpdsum + rwdsum;
                    ExamBLL bll = new ExamBLL();
                    try
                    {
                        bll.AddEntity(c);
                        return Content("<script>alert('创建成功！');location.href='/Course/Exammba'</script>");
                    }
                    catch (Exception)
                    {
                        return Content("<script>alert('创建失败！');location.href='/Course/Exammba'</script>");
                    }
                }
                #endregion

                #region 困难难度
                else
                {
                    //困难单选题
                    if (sdxsum == 0)
                    {
                        c.SingleChoiceID = null;
                    }
                    else
                    {
                        List<Select> jd1 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 3 && p.Choice == 0).ToList();
                        foreach (var a in jd1)
                        {
                            c.SingleChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.SingleChoiceID = c.SingleChoiceID.Substring(0, c.SingleChoiceID.Length - 1);
                    }

                    //困难多选题
                    if (ddxsum == 0)
                    {
                        c.ChoiceID = null;
                    }
                    else
                    {
                        List<Select> jd2 = sbll.getEntityList(p => true).Where(p => p.Difficulty == 3 && p.Choice == 1).ToList();
                        foreach (var a in jd2)
                        {
                            c.ChoiceID += a.SelectId.ToString() + ",";
                        }
                        c.ChoiceID = c.ChoiceID.Substring(0, c.ChoiceID.Length - 1);
                    }

                    //困难填空题
                    if (gtksum == 0)
                    {
                        c.FillingID = null;
                    }
                    else
                    {
                        List<GapFilling> tk = gbll.getEntityList(p => true).Where(p => p.Difficulty == 3).ToList();
                        foreach (var a in tk)
                        {
                            c.FillingID += a.GapFillingId.ToString() + ",";
                        }
                        c.FillingID = c.FillingID.Substring(0, c.FillingID.Length - 1);
                    }

                    //困难判断题
                    if (jpdsum == 0)
                    {
                        c.JudgeID = null;
                    }
                    else
                    {
                        List<Judge> jdpd = jbll.getEntityList(p => true).Where(p => p.Difficulty == 3).ToList();
                        foreach (var a in jdpd)
                        {
                            c.JudgeID += a.JudgeId.ToString() + ",";
                        }
                        c.JudgeID = c.JudgeID.Substring(0, c.JudgeID.Length - 1);
                    }

                    //困难问答题
                    if (rwdsum == 0)
                    {
                        c.SketchID = null;
                    }
                    else
                    {
                        List<Respond> jdwd = rbll.getEntityList(p => true).Where(p => p.Difficulty == 3).ToList();
                        foreach (var a in jdwd)
                        {
                            c.SketchID += a.RespondId.ToString() + ",";
                        }
                        c.SketchID = c.SketchID.Substring(0, c.SketchID.Length - 1);
                    }

                    c.Score = sdxsum * d1 + ddxsum * d2 + gtksum * g1 + jpdsum * j1 + rwdsum * r1;
                    c.queber = sdxsum + ddxsum + gtksum + jpdsum + rwdsum;
                    ExamBLL bll = new ExamBLL();
                    try
                    {
                        bll.AddEntity(c);
                        return Content("<script>alert('创建成功！');location.href='/Course/Exammba'</script>");
                    }
                    catch (Exception)
                    {
                        return Content("<script>alert('创建失败！');location.href='/Course/Exammba'</script>");
                    }
                }
                #endregion
            }
            #endregion
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CoursePrice1(Courses rcourse)
        {
            //根据Session["Courseid"]查询到单个课程信息
            int id = Convert.ToInt32(Session["Courseid"]);
            Courses course = coursebll.Search(id);
            //给单个课程赋新值        
            course.CPrice = rcourse.CPrice;  //课程价格
            if (coursebll.Edit(course))
            {
                return Content("<script>alert('保存成功！');location.href='/Course/CourseTeacher?id=" + id + "'</script>");
            }
            else
            {
                return Content("<script>alert('保存失败！'); location.href='/Course/CoursePrice=" + id + "'</script>");
            }
        }

        /// <summary>
        /// 教师设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CourseTeacher(int id)
        {
            if (Session["Uname"] != null)
            {
                //获取ID
                Session["Courseid"] = id;
                //根据ID找到单个课程信息
                Courses course = coursebll.Search(id);
                //获取教师集合并传至页面下拉框显示
                UserInfoBLL bll = new UserInfoBLL();
                List<LeEdu.MODEL.UserInfo> userlist = bll.getEntityList(p => true).Where(p => p.RoleId == 2 && p.TeacherCheck == 1).ToList();
                int Uid = Convert.ToInt32(Session["id"]);
                ViewBag.users = bll.Search(Uid);
                // ViewBag.xx=users.XingMing;
                ViewBag.UserInfoId = new SelectList(userlist, "UserInfoId", "XingMing", course.UserInfoId);
                return View(course);
            }
            else
            {
                return Content("<script>alert('请先登录');location.href='/Login/Index'</script>");
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CourseTeacher1(Courses rcourse)
        {
            //根据Session["Courseid"]查询到单个课程信息
            int id = Convert.ToInt32(Session["Courseid"]);
            Courses course = coursebll.Search(id);
            //给单个课程赋新值        
            course.UserInfoId = rcourse.UserInfoId;  //换个讲师
            if (coursebll.Edit(course))
            {
                return Content("<script>alert('保存成功！');location.href='/Course/CourseTeacher?id=" + id + "'</script>");
            }
            else
            {
                return Content("<script>alert('保存失败！'); location.href='/Course/CourseTeacher=" + id + "'</script>");
            }
        }

        /// <summary>
        /// 学员管理
        /// </summary>
        /// <returns></returns>
        public ActionResult CourseStudents(int pageIndex = 1)
        {
            if (Session["User"] != null)
            {
                int pageSize = 2;
                List<Student> lst = db.Students.Where(p => p.UserInfo.RoleId == 1).ToList();
                int count = lst.Count();
                int pagecount = count / pageSize;
                if (count % pageSize > 1)
                {
                    pagecount += 1;
                }
                lst = lst.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageCount = pagecount;
                ViewBag.ss = lst;
                return View(lst);
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }

        /// <summary>
        /// 批阅完成
        /// </summary>
        /// <returns></returns>
        public ActionResult OverCheckExam()
        {
            return View();
        }

        /// <summary>
        /// 试题管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Exammba()
        {
            ExamBLL bll = new ExamBLL();
            return View(bll.getEntityList(p => p.ExamID == 1));
        }

        /// <summary>
        /// 编辑试卷
        /// </summary>
        /// <returns></returns>
        public ActionResult EditExam()
        {
            return View();
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <returns></returns>
        public ActionResult EditState(int id)
        {
            var a = Eabll.getEntity(p => p.ExamID == id);
            if (a.PubState == 0)
            {
                a.PubState = 1;
            }
            else if (a.PubState == 1)
            {
                a.PubState = 0;
            }
            return Eabll.Edit(a) ? RedirectToAction("Exammba") : RedirectToAction("Exammba");
        }

        /// <summary>
        /// 试题管理的预览
        /// </summary>
        /// <returns></returns>
        public ActionResult Exampreview(int id)
        {
            BLL.ExamBLL bll = new ExamBLL();
            ViewBag.eid = id;
            return View(bll.getEntity(p => p.ExamID == id));
        }

        /// <summary>
        /// 试题管理的删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ExamDelete(int id)
        {
            ExamBLL bll = new ExamBLL();
            Exam x = new Exam();
            x.ExamID = id;
            try
            {
                bll.Del(x);
                return Content("<script>alert('删除成功!');location.href='/Course/Exammba'</script>");
            }
            catch (Exception)
            {
                return Content("<script>alert('删除失败!');location.href='/Course/Exammba'</script>");
            }
        }
        /// <summary>
        /// 添加学员
        /// </summary>
        /// <param name="stu"></param>
        /// <returns></returns>
        public ActionResult AddStudents(FormCollection col)
        {

            Student stu = new Student();

            if (col["StuName"] != null)
            {
                foreach (var item in new UserInfoBLL().getEntityList(s=>true))
                {
                    if(item.Email==col["StuName"])
                    {
                        stu.UserInfoId=item.UserInfoId;
                    }else if(item.Uname==col["StuName"])
                    {
                        stu.UserInfoId = item.UserInfoId;
                    }
                    else if (item.PhoneNum == col["StuName"])
                    {
                        stu.UserInfoId = item.UserInfoId;
                    }
                    else
                    {
                        Content("<script>alert('dsfsdfdsf！！！');location.href='/Course/CourseStudents'</script>");
                    }
                }           
               
            }
            stu.CoursesId= Convert.ToInt32(Session["Courseid"]);
            stu.StudentPrice = Convert.ToDecimal(col["StudentPrice"]);
            stu.StudentRemark = col["StudentRemark"];
            stu.StudentDateTime = DateTime.Now;
            StuBLL sbll = new StuBLL();
            foreach (var item in new UserInfoBLL().getEntityList(s=>true))         
            {
                if (item.RoleId == 1)
                {
                    if (sbll.AddEntity(stu))
                    {
                        return Content("<script>alert('添加成功！！！');location.href='/Course/CourseStudents'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('添加失败！！！');location.href='/Course/CourseStudents'</script>");
                    }
                }
            }
            return View();
        }
        /// <summary>
        /// 课程考试页面
        /// </summary>
        /// <returns></returns>
        public ActionResult LessonCExam()
        {
            return View();
        }

        /// <summary>
        /// 答题交卷页面
        /// </summary>
        /// <returns></returns>
        public ActionResult SubmitExam(int id)
        {
            BLL.ExamBLL bll = new ExamBLL();
            BLL.HourBLL hbll = new HourBLL();
            int aid = Convert.ToInt16(hbll.getEntity(p => p.HourId == id).ExamID);
            ViewBag.eid = aid;
            return View(bll.getEntity(p => p.ExamID == aid));
        }

        public ActionResult SubmitExamAdd()
        {
            return View();
        }

        public ActionResult sss()
        {
            return View();
        }
    }
}
